package com.zzusedating.androidapp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.zzusedating.androidapp.customlayout.TextViewWithClearButton;
import com.zzusedating.androidapp.tools.ConstantsTools;
import com.zzusedating.androidapp.tools.MyApplication;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class ForgetPasswordActivity extends BaseActivity {
    private static final String TAG = "ForgetPasswordActivity";
    private static final int RESET_SUCCESS_I = 140;
    private final int VERIFY_CODE_SENT_I = 141;
    private final int EMAIL_FORMAT_ERROR_I = 144;
    private final int VERIFY_ERROR_I = 145;
    private final int USER_NOT_FOUND_I = 143;

    private final String RESET_SUCCESS_ = "修改成功，请重新登录";
    private final String USER_NOT_FOUND_ = "用户不存在";
    private final String VERIFY_CODE_SENT_ = "验证码已发送";
    private final String EMAIL_FORMAT_ = "邮箱格式不正确";
    private final String VERIFY_ERROR_ = "验证码错误";

    private View.OnClickListener verifyListener;
    private View.OnClickListener finishListener;

    private Callback verifyCallback;
    private Callback finishCallback;
    private Handler handler;

    private Button finishButton;
    private TextViewWithClearButton verifyView, emailView, passwordView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password_layout);

        initCallback();
        initListener();

        verifyView = findViewById(R.id.ForgetPassword_VerifyCodeTVWCBView);
        emailView = findViewById(R.id.ForgetPassword_EmailTVWCBView);
        passwordView = findViewById(R.id.ForgetPassword_NewPasswordTVWCBView);
        finishButton = findViewById(R.id.ForgetPassword_FinishButton);

        finishButton.setOnClickListener(finishListener);
        verifyView.setOnClickListenerToVerifyCode(verifyListener);
    }

    @Override
    protected void initListener() {
        verifyListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = emailView.getText();
                if (TextUtils.isEmpty(email)){
                    Toast.makeText(ForgetPasswordActivity.this, "请填写邮箱", Toast.LENGTH_SHORT).show();
                    return;
                }
                Request request = new Request.Builder()
                        .get()
                        .url(String.format(ConstantsTools.RESET_PASSWORD_VERIFY, email))
                        .build();
                MyApplication.getClient().newCall(request).enqueue(verifyCallback);
            }
        };
        finishListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = emailView.getText();
                String verifyCode = verifyView.getText();
                String password = passwordView.getText();
                if (TextUtils.isEmpty(email) || TextUtils.isEmpty(verifyCode) || TextUtils.isEmpty(password)){
                    MyApplication.Toast("请完善信息");
                    return;
                }
                Request request = new Request.Builder()
                        .get()
                        .url(String.format(ConstantsTools.RESET_PASSWORD, verifyCode, password))
                        .build();
                MyApplication.getClient().newCall(request).enqueue(finishCallback);
            }
        };
    }

    @Override
    protected void initCallback() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what){
                    case USER_NOT_FOUND_I:
                        MyApplication.Toast(USER_NOT_FOUND_);
                        break;
                    case ConstantsTools.NETWORK_ERROR_I:
                        MyApplication.Toast(ConstantsTools.NETWORK_ERROR_);
                        break;
                    case VERIFY_CODE_SENT_I:
                        MyApplication.Toast(VERIFY_CODE_SENT_);
                        break;
                    case EMAIL_FORMAT_ERROR_I:
                        MyApplication.Toast(EMAIL_FORMAT_);
                        break;
                    case VERIFY_ERROR_I:
                        MyApplication.Toast(VERIFY_ERROR_);
                        break;
                    case RESET_SUCCESS_I:
                        MyApplication.Toast(RESET_SUCCESS_);
                        finish();
                        break;
                }
                return true;
            }
        });
        verifyCallback = new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendMessage(ConstantsTools.createMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() != 200){
                    Log.e(TAG, "onResponse: code: " + response.code());
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    if (jsonObject.getInt("status") == 1){
                        handler.sendMessage(ConstantsTools.createMessage(VERIFY_CODE_SENT_I));
                    }
                    else {
                        int code = jsonObject.getInt("code");
                        switch (code){
                            case 2:
                                handler.sendMessage(ConstantsTools.createMessage(EMAIL_FORMAT_ERROR_I));
                                break;
                            case 5:
                                handler.sendMessage(ConstantsTools.createMessage(USER_NOT_FOUND_I));
                                break;
                            default:
                                handler.sendMessage(ConstantsTools.createMessage());
                                break;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        finishCallback = new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendMessage(ConstantsTools.createMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() != 200){
                    Log.e(TAG, "onResponse: code: " + response.code());
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    if (jsonObject.getInt("status") == 1){
                        handler.sendMessage(ConstantsTools.createMessage(RESET_SUCCESS_I));
                    }
                    else {
                        if (jsonObject.getInt("code") == 3)
                            handler.sendMessage(ConstantsTools.createMessage(VERIFY_ERROR_I));
                        else
                            handler.sendMessage(ConstantsTools.createMessage());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
